<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script type="text/javascript" src="./lib/vue-2.4.0.js"></script>
    <link rel="stylesheet" href="./lib/bootstrap-3.3.7.css">
</head>
<body>

    <div id="app">
        <cmts @func="loadComments"></cmts>

        <ul class="list-group">
            <li class="list-group-item" v-for="item in list" :key="item.id">
                <span class="badge">评论人： {{ item.user }}</span>
                {{ item.content }}
            </li>
        </ul>
    </div>

    <template id="#tmpl">
        <div>
            <div class="form-group">
                <label>评论人:</label>
                <input type="text" class="form-control" v-model="user" />
            </div>

             <div class="form-group">
                <label>评论内容:</label>
                <input type="text" class="form-control" v-model="content" />
            </div>

            <div class="form-control">
            <input type="button" class="btn btn-primary" @click = "postComments" />
            </div>
        </div>
    </template>
    <script type="text/javascript">
    var commentBox = {
        template: '#tmpl',
        data(){
            return {
                user: '',
                content: ''
            }
        },
        methods:{
            postComment(){
                var comment = { id: Date.now(), user: this.user, content: this.content };
                var list = JSON.parse( localStorage.getItem('cmts' || '[]') );
                list.unshift( comment );
                localStorage.setItem( 'cmts', JSON.parse(list) );
                this.user = this.comment = '';
                this.$emit('func');
            }
        }
    };

        // 创建 Vue实例，得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {
                list:[
                    { user: '徐', content: '1' },
                    { user: '兴', content: '2' },
                    { user: '丰', content: '3' }
                ]
            },
            created(){
                this.loadComments();
            }
            methods: {
                loadComments(){
                    var list = JSON.parse( localStorage.getItem( 'cmts' ) || '[]');
                    this.list = list;
                }
            },
            components: {
                cmts: commentBox,
            }
        });
    </script>
</body>
</html>